package infostroy.bookagolf.components.panels;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Base panel that supports dragging. Override paintComponent
 * method for customize it.
 */
public class BaseDraggablePanel extends JPanel {

    /**
     * Parent container
     */
    private Container window;

    /**
     * X coordinate when mouse was clicked on this component
     */
    private int x;
    /**
     * Y coordinate when mouse was clicked on this component
     */
    private int y;

    public BaseDraggablePanel(Container window) {
        this.window = window;
        this.initMouseListeners();
    }

    /**
     * Adds mouseClicked and mouseDragged  listeners to component
     * that allow to drag it.
     */
    private void initMouseListeners() {
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                x = e.getX();
                y = e.getY();
            }
        });

        this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int newX = (int) window.getLocation().getX() + e.getX()
                        - x;
                int newY = (int) window.getLocation().getY() + e.getY()
                        - y;
                window.setLocation(newX, newY);
            }
        });
    }

    public Container getWindow() {
        return window;
    }
}
